package com.github.pig.admin.service.zhgl.houseowner.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pig.admin.mapper.device.GuardDeviceMapper;
import com.github.pig.admin.mapper.zhgl.house.UnitHouseMapper;
import com.github.pig.admin.mapper.zhgl.houseowner.HouseOwnerMapper;
import com.github.pig.admin.model.device.GuardDevice;
import com.github.pig.admin.model.entity.SysUserRole;
import com.github.pig.admin.model.zhgl.house.UnitHouse;
import com.github.pig.admin.model.zhgl.house.UnitHouseBean;
import com.github.pig.admin.model.zhgl.houseowner.HouseOwner;
import com.github.pig.admin.service.sys.SysRoleService;
import com.github.pig.admin.service.sys.SysUserRoleService;
import com.github.pig.admin.service.zhgl.house.IUnitHouseService;
import com.github.pig.admin.service.zhgl.houseowner.IHouseOwnerService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.ListUtils;
import sun.reflect.annotation.ExceptionProxy;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 业主基本信息表 服务实现类
 * </p>
 *
 * @author lxm
 * @since 2018-06-20
 */
@Service
public class HouseOwnerServiceImpl extends ServiceImpl<HouseOwnerMapper, HouseOwner> implements IHouseOwnerService {
    @Autowired
    private HouseOwnerMapper houseOwnerMapper;
    @Autowired
    private UnitHouseMapper unitHouseMapper;
    @Autowired
    private GuardDeviceMapper deviceMapper;
    @Autowired
    private IUnitHouseService unitHouseService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysRoleService sysRoleService;


    @Override
    public Page querHouseOwnerGrid(Page<HouseOwner> page, HouseOwner houseOwner) {
        List<HouseOwner> list = houseOwnerMapper.querHouseOwnerGrid(page, houseOwner);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<UnitHouseBean> queryUnitHouse(UnitHouseBean unithouse) {
        return unitHouseMapper.queryUnitHouseGrid(unithouse);
    }

    @Override
    public UnitHouseBean getUnitHouseBean(String buildingName, String unitName, String houseName, String communityId) {
        return unitHouseMapper.getUnitHouseBean(buildingName, unitName, houseName, communityId);
    }
    //判断是否超过门禁最大人数限制，如果没有直接更新

    /**
     * 步骤
     * 1、查询添加业主角色
     * 2、角色相对应的设备
     * 3、查询设备总数以及当前人数+1
     * TODO  编辑时，控制当前人数比较困难，可能会多加1
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<GuardDevice> isOverLimit(HouseOwner houseOwner) {
        if (StringUtils.isBlank(houseOwner.getRoleId())) {
            return null;
        }
        //1
        String[] rIds = houseOwner.getRoleId().split(",");
        StringBuilder sb = new StringBuilder();
        List<GuardDevice> deviceList = new ArrayList<>();
        for (String rid : rIds) {
            //2
            List<GuardDevice> list = deviceMapper.getDeviceId(rid);
            //3
            list.forEach(device -> {
                if (device.getUserMax() != null && device.getUserMax() < (device.getUserNow() == null ? 1 : device.getUserNow() + 1)) {
                    deviceList.add(device);
                } else {
                    sb.append(device.getId() + ",");
                }
            });
        }
        //更新所有设备的当前用户数
        if (deviceList == null || deviceList.size() == 0) {
            deviceMapper.updateUserSumByIds(sb.substring(0, sb.length() - 1), 1);
        }
        return deviceList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxJson addOwner(HouseOwner houseOwner) {
        AjaxJson json = new AjaxJson();
        //判断是否超过门禁最大人数限制
        List<GuardDevice> devices = this.isOverLimit(houseOwner);
        if (devices != null && devices.size() > 0) {
            StringBuilder sb = new StringBuilder();
            devices.forEach(device -> {
                sb.append(device.getDeviceName());
                sb.append(",");
            });
            json.setSuccess(false);
            json.setMsg("添加失败,设备：" + sb.substring(0, sb.length() - 1) + " 容量已经超出上限，详细问题请咨询厂家。");
            return json;
        }
        //默认业主本人
        houseOwner.setRelation("1");
        if (this.insert(houseOwner)) {
            //更改房屋状态 变更为已出售
            UnitHouse unitHouse = new UnitHouse();
            unitHouse.setId(houseOwner.getHouseId());
            unitHouse.setStatus("2");
            unitHouseMapper.updateById(unitHouse);
            json.setSuccess(true);
            json.setMsg("添加成功。");
        } else {
            json.setSuccess(false);
            json.setMsg("添加失败。");
        }

        return json;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delOwner(HouseOwner houseOwner) {
        houseOwnerMapper.updateById(houseOwner);
        if (StringUtils.isBlank(houseOwner.getRoleId())) {
            return true;
        }
        String[] rIds = houseOwner.getRoleId().split(",");
        StringBuilder sb = new StringBuilder();
        for (String rid : rIds) {
            //获取所有的设备
            List<GuardDevice> list = deviceMapper.getDeviceId(rid);
            list.forEach(device -> {
                sb.append(device.getId() + ",");
            });
        }
        //更新所有设备的当前用户数
        deviceMapper.updateUserSumByIds(sb.substring(0, sb.length() - 1), -1);
        return true;
    }

    /**
     * 批量删除业主
     *
     * @param list
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delOwnerList(List<HouseOwner> list) {

        StringBuilder sb = new StringBuilder();
        for (HouseOwner houseOwner : list) {
            houseOwner.setDelFlag(CommonConstant.STATUS_DEL);
            if (StringUtils.isBlank(houseOwner.getRoleId())) {
                continue;
            }
            String[] rIds = houseOwner.getRoleId().split(",");
            for (String rid : rIds) {
                //获取所有的设备
                List<GuardDevice> devices = deviceMapper.getDeviceId(rid);
                devices.forEach(device -> {
                    sb.append(device.getId() + ",");
                });
            }
        }
        this.updateBatchById(list);
        //更新所有设备的当前用户数
        deviceMapper.updateUserSumByIds(sb.substring(0, sb.length() - 1), -list.size());
        return true;
    }

    /**
     * 导入业主信息
     *
     * @param insertList     业主列表
     * @param unitHousesList 单元列表
     * @param roleIds        角色IDs
     * @param size
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxJson batchAddOwner(List<HouseOwner> insertList, List<UnitHouse> unitHousesList, String roleIds, int size) {
        AjaxJson json = new AjaxJson();
        StringBuilder sb = new StringBuilder();
        StringBuilder deviceNames = new StringBuilder();
        Map<Integer,Integer> map = new HashMap<>();
        if (StringUtils.isNotBlank(roleIds)) {
            String[] rIds = roleIds.split(",");
            for (String rid : rIds) {
                List<GuardDevice> list = deviceMapper.getDeviceId(rid);
                list.forEach(device -> {
                    //因为不好统计导入时每个设备需要插入多少人 所以使用map累加
                    Integer count = map.get(device.getId());
                    if (device.getUserMax() != null && device.getUserMax() < (device.getUserNow() == null ? 1 : device.getUserNow() +( count == null ? 1 : count + 1))) {
                        if(!deviceNames.toString().contains(device.getDeviceName())){
                            deviceNames.append(device.getDeviceName() + ",");
                        }

                    } else {
                        map.put(device.getId(), count == null ? 1 : count + 1);
                        sb.append(device.getId() + ",");
                    }
                });
            }
        }
        //更新所有设备的当前用户数
        if (StringUtils.isNotBlank(deviceNames)) {
            json.setSuccess(false);
            json.setMsg("导入失败，" + deviceNames.substring(0, deviceNames.length() - 1) + " 容量已经超出上限，详细问题请咨询厂家。");
            return json;
        } else {
            if (StringUtils.isNotBlank(sb)) {
               Map<String, Integer> maps = getCountMaps(sb.substring(0, sb.length() - 1));
                for (Map.Entry<String, Integer> entry : maps.entrySet()) {
                    deviceMapper.updateUserSumByIds(entry.getKey(),entry.getValue());
                }
            }
        }
        if(insertList.size()>0){
            this.insertBatch(insertList);
        }
        //更改房屋状态
        if(unitHousesList.size()>0){
            unitHouseService.updateBatchById(unitHousesList);
        }
        json.setSuccess(true);
        json.setMsg("成功导入：" + insertList.size() + "行,重复房屋或房屋错误" + (size - insertList.size()) + "行");
        return json;
    }

    public static Map<String, Integer> getCountMaps(String str) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        String[] ids = str.split(",");
        for (int i = 0; i < ids.length; i++) {
            Integer count = map.get(ids[i]);
            map.put(ids[i], count == null ? 1 : count + 1);
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handOverHouse(HouseOwner houseOwner,AjaxJson json) {
        EntityWrapper selectOwner = new EntityWrapper();
        selectOwner.eq("relation", "1");
        selectOwner.eq(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        selectOwner.eq("house_id", houseOwner.getHouseId());
        HouseOwner owner = this.selectOne(selectOwner);
        if(owner==null){
            json.setSuccess(false);
            json.setMsg("该房屋未绑定业主，无需移交。");
            return;
        }
        //将老房主信息重新保存
        HouseOwner newHouseOwner = new HouseOwner();
        newHouseOwner.setDefaultHouse(owner.getDefaultHouse());
        newHouseOwner.setImgPath(owner.getImgPath());
        newHouseOwner.setPhone(owner.getPhone());
        newHouseOwner.setName(owner.getName());
        newHouseOwner.setCardNumber(owner.getCardNumber());
        newHouseOwner.setAddress(owner.getAddress());
        newHouseOwner.setSex(owner.getSex());
        newHouseOwner.setDelFlag(CommonConstant.STATUS_DEL);
        newHouseOwner.setRelation(owner.getRelation());
        newHouseOwner.setHouseId(owner.getHouseId());
        newHouseOwner.setRoleId(owner.getRoleId());

        //删除原先房子的所有者
        EntityWrapper delOwner = new EntityWrapper();
        delOwner.eq("house_id", houseOwner.getHouseId());
        delOwner.eq("del_flag", CommonConstant.STATUS_NORMAL);
        List<HouseOwner> delOwners = houseOwnerMapper.selectList(delOwner);
        for (HouseOwner bean : delOwners) {
            bean.setDelFlag(CommonConstant.STATUS_DEL);
        }
        this.updateBatchById(delOwners);
        houseOwnerMapper.insert(newHouseOwner);
        //变更新房主，集成原先房主权限
        owner.setSex(houseOwner.getSex());
        owner.setAddress(houseOwner.getAddress());
        owner.setCardNumber(houseOwner.getCardNumber());
        owner.setName(houseOwner.getName());
        owner.setPhone(houseOwner.getPhone());
        owner.setImgPath(houseOwner.getImgPath());
        owner.setDefaultHouse("0");
        owner.setUserId(0);
        this.updateById(owner);

        //设备更新当前用户数
        String ids[] = owner.getRoleId() == null ? null : owner.getRoleId().split(",");
        if (ids != null && ids.length != 0) {
            StringBuilder sb = new StringBuilder();
            for (String rid : ids) {
                //获取所有的设备
                List<GuardDevice> devices = deviceMapper.getDeviceId(rid);

                devices.forEach(device -> {
                    sb.append(device.getId() + ",");
                });
            }
            deviceMapper.updateUserSumByIds(sb.substring(0, sb.length() - 1), 1 - delOwners.size());
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxJson updateOwner(HouseOwner houseOwner) {
        AjaxJson json = new AjaxJson();
        json.setSuccess(true);
        HouseOwner oldOwner = houseOwnerMapper.selectById(houseOwner.getId());
        if (this.updateById(houseOwner)) {
                //更新 sys_user_role
                String[] newRoleIds = houseOwner.getRoleId() == null ? null : houseOwner.getRoleId().split(",");
                String oldRIds[] = oldOwner.getRoleId() == null ? null : oldOwner.getRoleId().split(",");
                List<String> add = new ArrayList<>();
                List<String> del = new ArrayList<>();
                if (newRoleIds == null) {
                    if (oldRIds == null) {
                        json.setMsg("更新成功");
                        return json;
                    } else {
                        for (String id : oldRIds) {
                            del.add(id);
                        }
                    }
                } else {
                    if (oldRIds == null) {
                        for (String id : newRoleIds) {
                            add.add(id);
                        }
                    } else {
                        //因为asList 生成的是java.util.Arrays类中的一个内部类 不支持增删，所以外层进行包装
                        List<String> delRoles = new ArrayList<>(Arrays.asList(oldRIds));
                        u1:
                        for (String nr : newRoleIds) {
                            u2:
                            for (String or : oldRIds) {
                                if (nr.equals(or)) {
                                    delRoles.remove(or);
                                    continue u1;
                                }
                            }
                            add.add(nr);
                        }
                        if (delRoles.size() > 0) {
                            for (String id : delRoles) {
                                del.add(id);
                            }
                        }
                    }
                }
                //新增的角色
                StringBuilder addRoles = new StringBuilder();
                StringBuilder names = new StringBuilder();
                if (!ListUtils.isEmpty(add)) {
                    for (String rid : add) {
                        //获取所有的设备
                        List<GuardDevice> devices = deviceMapper.getDeviceId(rid);
                        devices.forEach(device -> {
                            if (device.getUserMax() != null && device.getUserMax() < (device.getUserNow() == null ? 1 : device.getUserNow() + 1)) {
                                names.append(device.getDeviceName() + ",");
                            } else {
                                addRoles.append(device.getId() + ",");
                            }
                        });
                    }
                }
                if (StringUtils.isNotBlank(names)) {
                    json.setSuccess(false);
                    json.setMsg("更新失败，" + names.substring(0, names.length() - 1) + " 容量已经超出上限，详细问题请咨询厂家。");
                    return json;
                } else {
                    if (StringUtils.isNotBlank(addRoles)) {
                        deviceMapper.updateUserSumByIds(addRoles.substring(0, addRoles.length() - 1), 1);
                    }
                }
                //删除的角色
                StringBuilder sb = new StringBuilder();
                for (String rid : del) {
                    //获取所有的设备
                    List<GuardDevice> devices = deviceMapper.getDeviceId(rid);
                    devices.forEach(device -> {
                        sb.append(device.getId() + ",");
                    });
                }
                if (StringUtils.isNotBlank(sb)) {
                    deviceMapper.updateUserSumByIds(sb.substring(0, sb.length() - 1), -1);
                }
                if (houseOwner.getUserId() > 0) {
                    //新增角色
                    if (add != null) {
                        for (String roleId : add) {
                            SysUserRole sysUserRole = new SysUserRole();
                            sysUserRole.setUserId(houseOwner.getUserId());
                            sysUserRole.setRoleId(Integer.valueOf(roleId));
                            sysUserRole.setType(CommonConstant.USER_ROLE_TYPE_OWNER);
                            sysUserRole.insert();
                        }
                    }
                    //删除角色
                    if (del != null) {
                        for (String roleId : del) {
                            EntityWrapper wrapper = new EntityWrapper();
                            wrapper.eq("user_id", houseOwner.getUserId());
                            wrapper.eq("role_id", roleId);
                            wrapper.eq("type", CommonConstant.USER_ROLE_TYPE_OWNER);
                            sysUserRoleService.delete(wrapper);
                        }
                    }
                }
            json.setMsg("更新成功");
        }
        return json;
    }


    public static void main(String[] args) {
       /* String[] newRoleIds = {"1", "2", "3"};
        String[] oldRIds = {"2", "3"};
        for (String nr : newRoleIds) {
            for (String or : oldRIds) {
                if (nr.equals(or)) {
                    break;
                }
                System.out.println(nr);
            }
        }*/
       String bd = ",,1,2,3,4,5,6,7,88,7,3,6,2,5,7,7,7,7,5,4,3,";
        Map<String, Integer> map = getCountMaps(bd);
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
    }
}
